import java.text.SimpleDateFormat

class CmsTagLib {
  static namespace = "cms"
  def babyService
  def authenticateService

  def isManager = {attrs, body ->
    def person = null
    if(attrs.baby instanceof Baby){
      person = attrs.baby.person
    } else if (attrs.person instanceof Person) {
      person = attrs.person
    } else {
      return
    }
    def p = authenticateService.userDomain()
    if(p && p.id == person.id){
      out << body()
    }
  }

  def growings = {attrs, body ->
    def baby = null
    if(attrs.baby instanceof Baby){
      baby = attrs.baby
    } else if(attrs.baby instanceof String){
      baby = Baby.get(attrs.baby) 
    }
    def grows = []
    if (baby) {
      grows = Growing.findAllByBaby(baby, [sort: 'dateCreated', order: 'desc', max: '10'])
    }
    out << body(growingList: grows)
  }

  def toDos = {attrs, body ->
    def baby = Baby.get(1)
    def taskList = []
    def total = 0
    def max = 10
    if (attrs.max) max = attrs.max.toInteger()
    if (baby) {
      def tasks = Task.findAllByBabyAndTaskType(baby, Task.TASK_TYPE_SHOULD_DO, [max: max, order: 'desc', sort: 'dateCreated'])
      taskList = tasks //Collections.sort(tasks)
      total = Task.countByBabyAndTaskType(baby, Task.TASK_TYPE_SHOULD_DO)
    }
    out << body(taskList: taskList, total: total)
  }

  def toCares = {attrs, body ->
    def baby = Baby.get(1)
    def taskList = []
    def total = 0
    def max = 10
    if (attrs.max) max = attrs.max.toInteger()
    if (baby) {
      def tasks = Task.findAllByBabyAndTaskType(baby, Task.TASK_TYPE_SHOULD_CARE, [max: max, order: 'desc', sort: 'dateCreated'])
      taskList = Collections.sort(tasks)
      total = Task.countByBabyAndTaskType(baby, Task.TASK_TYPE_SHOULD_CARE)
    }
    out << body(taskList: taskList, total: total)
  }


  def findBaby(attrs) {
    if (attrs.baby instanceof Baby) {
      baby = attrs.baby
    } else if (attrs.baby instanceof String) {
      baby = Baby.get(attrs.baby)
    }
    return baby
  }

  def shortContent = {attrs, body ->
    if (attrs.content) {
      def max = attrs.max ? attrs.max.toInteger() : 20
      if (max > attrs.content.length()) {
        out << attrs.content.encodeAsHTML()
      } else {
        out << attrs.content.substring(0, max).encodeAsHTML() << "..."
      }
    }
  }

  def formatContent = {attrs, body ->
    def content = body()
    if (content) {
      if (content.indexOf('<br') > 0) {
        out << content
      } else {
        out << content.replaceAll('\r\n', '<br />')
      }
    }
  }
  def formatDate = {attrs ->
    def date
    if (attrs.containsKey('date')) {
      date = attrs.get('date')
      if (date == null) return
    }
    else {
      date = new Date()
    }

    def today = new Date()
    def formated = ''
    def week = date.getAt(Calendar.DAY_OF_WEEK) - 1
    def simpleDateFormat1 = new SimpleDateFormat(message(code: 'dateformat.long'))
    def simpleDateFormat2 = new SimpleDateFormat(message(code: 'dateformat.short'))
    if ((today.getAt(Calendar.YEAR) - date.getAt(Calendar.YEAR)) > 0) {
      formated = simpleDateFormat1.format(date) + ' ' + message(code: "week.${week}")
    } else if ((today.getAt(Calendar.DAY_OF_YEAR) - date.getAt(Calendar.DAY_OF_YEAR)) > 2) {
      formated = simpleDateFormat1.format(date) + ' ' + message(code: "week.${week}")
    } else if ((today.getAt(Calendar.DAY_OF_YEAR) - date.getAt(Calendar.DAY_OF_YEAR)) == 2) {
      formated = message(code: 'daybeforyestaday') + simpleDateFormat2.format(date) + ' ' + message(code: "week.${week}")
    } else if ((today.getAt(Calendar.DAY_OF_YEAR) - date.getAt(Calendar.DAY_OF_YEAR)) == 1) {
      formated = message(code: 'yestaday') + simpleDateFormat2.format(date) + ' ' + message(code: "week.${week}")
    } else {
      def minus = today.getTime() - date.getTime()
      def hour = (minus / 3600000).toInteger()
      def minute = ((minus % 3600000) / 60000).toInteger()
      def second = (((minus % 3600000) % 60000) / 1000).toInteger()
      formated = message(code: 'today') + simpleDateFormat2.format(date) + ' ('
      if (hour > 0) formated = formated + hour + message(code: 'hour')
      if (minute > 0) formated = formated + minute + message(code: 'minute')
      if (second > 0) formated = formated + second + message(code: 'second')
      else if (hour == 0 && minute == 0) formated = formated + second + message(code: 'second')
      formated = formated + message(code: 'ago') + ')'
    }
    out << formated
  }

  def stageEntry = {attrs, body ->
    if (attrs.catalog && attrs.stage) {
      def catalog = Catalog.get(attrs.catalog)
      if (catalog) {
        def sql = "from Entry as t where t.catalog = :catalog and t.stage <= :startStage order by t.stage desc"
        def entryList = Entry.findAll(sql, [catalog: catalog, startStage: attrs.stage], [max: 1])
        if (entryList) {
          out << body(entry: entryList[0])
        }
      }
    }
  }

  def service = {attrs, body ->
    out << body(babyService: babyService)
  }

  def caseEntries = {attrs, body ->
    def name
    if (attrs.plan) {
      def plan = Plan.get(attrs.plan)
      name = plan.name
    } else if (attrs.name) {
      name = attrs.name
    }

    def _case = Case.findByName(name)
    if (_case?.catalogId) {
      def entryList = Entry.findAllByCatalog(Catalog.get(_case.catalogId))
      if (entryList) {
        out << body(entryList: entryList)
      }
    }

  }

  def entries = {attrs, body ->
    if (attrs['case']) {
      def caseRootCatalog = Catalog.get(4)
      def catalogList = Catalog.findAllByNameAndParent(attrs['case'], caseRootCatalog)
      if (catalogList) {
        def catalog = catalogList[0]
        def entries = Entry.findAllByCatalog(catalog)
        out << body(entryList: entries)
        return
      }
    }
    if (attrs.catalog) {
      def catalog = Catalog.get(attrs.catalog)
      def max = attrs.max ? attrs.max.toInteger() : 10
      def entries = Entry.findAllByCatalog(catalog, [max: max])
      out << body(entryList: entries)
      return
    }
  }

  def entry = {attrs, body ->
    if (attrs.id) {
      def entry = Entry.get(attrs.id)
      out << body(entry: entry)
    }
  }

  def nextEntry = {attrs, body ->
    def entry = Entry.get(attrs.id)
    if (entry) {
      def entryList = Entry.findAllByCatalogAndIdGreaterThan(entry.catalog, entry.id)
      if (entryList) {
        entry = entryList[0]
        out << body(entry:entry)
      }
    }
  }

  def plan = {attrs, body ->
    if (attrs.id) {
      def plan = Plan.get(attrs.id)
      out << body(plan: plan)
    }
  }

  def headImg = {attrs, body ->
    if (attrs.baby instanceof Baby) {
      def baby = attrs.baby
      if (baby.headImg) {
        def img = baby.headImg
        def imgName = img.substring(0, img.lastIndexOf('.'))
        def imgExt = img.substring(img.lastIndexOf('.'))
        def headImg = imgName + '_50' + imgExt
        out << "<img alt=\"${baby.nickName}\" src=\"/yuying${headImg}\"/>"
      } else {
        out << "<img alt=\"${baby.nickName}\" src=\"${createLinkTo(dir: 'images', file: 'default.jpg')}\"/>"
      }

    }
  }
}
